<template>
  <div class="sdy-cate">
    <Teleport to=".header">
      <header-com></header-com>
    </Teleport>

    <div class="slide">
      <van-sidebar @change="slideBarChangeHandler" v-model="index">
        <van-sidebar-item
          v-for="item in cateList"
          :key="item"
          :title="item.trim()" />
      </van-sidebar>
    </div>

    <div class="container">
      <div
        v-for="(item, index) in goodsList"
        :key="index"
        class="box">
        <div class="title">{{ item.brandname }}</div>
        <van-grid :column-num="3">
          <van-grid-item
            v-for="value in item.goods"
            :key="value.proid"
            icon="photo-o" >
            <van-image style="width: 42px; height: 42px;" :src="value.img1" />
            <p>{{ value.proname }}</p>
          </van-grid-item>
        </van-grid>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import HeaderCom from '@/components/header.vue'
import { ref, onMounted } from 'vue'
import { getCategoriesList, getGoodsByCategories, getGoodsByCateAndBrand } from '@/apis/goods'

interface Goods {
  catename: string
  brandname: string
  goods: Array<{ proid: string, [key: string]: any }>
}

// 当前导航索引
const index = ref<number>(0)

// 请求数据渲染页面
// 准备一个变量表示分类列表
const cateList = ref<string[]>([])

// 准备一个变量表示商品列表
const goodsList = ref<Goods[]>([])

// 导航条改变事件
const slideBarChangeHandler = (index: number) => {
  // 让 goodsList 置空
  goodsList.value = []
  // 拿到当前分类
  getGoodsByCate(cateList.value[index])
}

// 准备一个请求某分类产品的方法
const getGoodsByCate = async (cate: string) => {
  // 拿到的是 分类下的 品牌
  const res = await getGoodsByCategories(cate)

  // 根据 分类 和 品牌 拿到对应的数据
  // 该分类内有多少个品牌, 请求多少个数据
  res.data.forEach(async (item: { brand: string }) => {
    const info = await getGoodsByCateAndBrand(item.brand, cate)

    // 组装数据
    goodsList.value.push({
      catename: cate,
      brandname: item.brand,
      goods: info.data
    })
  })

  console.log(goodsList.value)
}

onMounted(async () => {
  const res = await getCategoriesList()
  cateList.value = res.data

  slideBarChangeHandler(0)
})
</script>

<style lang="scss" scoped>
.sdy-cate {
  height: 100%;
  display: flex;
  overflow: hidden;

  > .slide {
    width: 80px;
    height: 100%;
    overflow: hidden;
  }

  > .container {
    flex: 1;
    box-sizing: border-box;
    padding: 10px;
    overflow: auto;

    > .box {
      margin-top: 30px;
    }
  }
}
</style>
